package cc.wanforme.st.server.base.controller;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;

import cc.wanforme.st.server.base.entity.Admin;
import cc.wanforme.st.server.base.service.IAdminService;
import cc.wanforme.st.server.vo.ResMessage;
import cc.wanforme.st.server.vo.SearchQueryVo;
import cc.wanforme.st.server.vo.base.AdminVo;

/** 用户控制层
 * @author wanne
 * 2022年3月12日
 */
@Controller
@RequestMapping("/base/admin")
public class AdminController {

	@Autowired
	private IAdminService adminService;
	
	@PostMapping("/add")
	@PreAuthorize("hasAuthority('admin:add')")
	@ResponseBody
	public ResMessage<Admin> add(@RequestBody Admin admin) {
		adminService.saveVo(admin);
		admin.setPassword(null);
		return ResMessage.success(admin);
	} 
	
	@PostMapping("/update")
	@PreAuthorize("hasAuthority('admin:update')")
	@ResponseBody
	public ResMessage<Void> update(@RequestBody Admin admin) {
		adminService.updateVo(admin);
		return ResMessage.success();
	}
	
	@PostMapping("/resetpwd")
	@PreAuthorize("hasAuthority('admin:update')")
	@ResponseBody
	public ResMessage<Void> resetPwd(@RequestBody Admin admin) {
		adminService.resetPwd(admin.getId(), admin.getPassword());
		return ResMessage.success();
	}
	
	@PostMapping("/del/{id}")
	@PreAuthorize("hasAuthority('admin:delete')")
	@ResponseBody
	public ResMessage<Void> del(@PathVariable String id ) {
		adminService.deleteAdmin(id);
		return ResMessage.success();
	}
	
	
	/** 查询，可以根据 name 和 adminname 模糊查询
	 * @param queryVo
	 * @return
	 */
	@PostMapping("/list")
	@PreAuthorize("hasAuthority('admin:list')")
	@ResponseBody
	public ResMessage<PageInfo<AdminVo>> list(@RequestBody SearchQueryVo<AdminVo> queryVo) {
		PageInfo<Admin> result = null;
		AdminVo param = queryVo.getParam();
		
		if(param!=null) {
			result = adminService.searchAdmins(queryVo.getPage(), queryVo.getSize(),
					param.getName(), param.getUsername());
		} else {
			result = adminService.searchAdmins(queryVo.getPage(), queryVo.getSize(),
					null, null);
		}
		
		PageInfo<AdminVo> resultPageInfo = new PageInfo<AdminVo>();
		BeanUtils.copyProperties(result, resultPageInfo, "list");
		if(result.getList() != null) {
			List<AdminVo> collect = result.getList().stream().map(AdminVo::new).collect(Collectors.toList());
			resultPageInfo.setList(collect);
		}
		
		return ResMessage.success(resultPageInfo);
	}
	
	
}
